from DrissionPage import Chromium, ChromiumOptions
import datetime
import platform

os_name = platform.system()

co = ChromiumOptions()
if os_name != 'Windows':
    co.set_argument('--no-sandbox')  # 关闭沙箱模式, 解决`$DISPLAY`报错
    co.headless(True)  # 开启无头模式, 解决`浏览器无法连接`报错
browser = Chromium(co)  # 实例化浏览器对象
tab = browser.latest_tab
tab.set.user_agent(
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'
)  # 设置user-agent
tab.get('https://wxg1425obh.com/plugin.php?id=k_misign:sign')
try:
    tab('点').click()
except:
    pass
try:
    tab('一天内不再提醒').click()
except:
    pass


def split_image(image_data):
    '''切割图片'''
    from PIL import Image
    import io
    import ddddocr
    # 打开原始图片
    # image = Image.open(input_path)
    image = Image.open(io.BytesIO(image_data))

    # 获取图片的宽度和高度
    width, height = 250, 450  #image.size

    # 设置每张小图的大小为100x100像素
    small_width = 250
    small_height = 150

    # 计算需要切割成多少张小图
    num_rows = height // small_height + (1 if height %
                                         small_height != 0 else 0)
    num_cols = width // small_width + (1 if width % small_width != 0 else 0)
    img = []
    for row in range(num_rows):
        for col in range(num_cols):
            left = col * small_width
            upper = row * small_height

            right = min((col + 1) * small_width, width)
            lower = min((row + 1) * small_height, height)

            box = (left, upper, right, lower)
            # 裁剪并保存小图
            cropped_image = image.crop(box)
            img.append(cropped_image)

    img_list = []
    for i in img:
        a = io.BytesIO()
        i.save(a, 'png')
        img_list.append(a)

    slide = ddddocr.DdddOcr(det=False, ocr=False, show_ad=False)

    # # res = slide.slide_comparison(img_io1.getvalue(),img_io2.getvalue())
    res = slide.slide_comparison(img_list[0].getvalue(),
                                 img_list[2].getvalue())

    return res['target']


def Verification_code(tab, wb):
    '''验证码识别'''  # 验证码识别
    # print(f'{wb}验证码识别中...')
    res = tab.listen.wait()  # 等待并获取一个数据包
    img = res.response.body
    url_r = split_image(img)[0]
    slider = tab('tag:div@@class=slide_block')
    slider.drag(url_r - 5, duration=1)
    tab.wait(2)
    if wb == '登录':
        if '成功' in tab('t:div@@id=tncode').text:
            tab('tag:button@@id=captcha_submit').click('js')
            tab.wait.load_start()
            # return print(f'{wb}验证码识别成功')
        else:
            tab('tag:div@@class=tncode_refresh', timeout=1).click()
            print('.', end='')
            Verification_code(tab, wb)
    else:
        if '成功' in tab('t:div@@id=tncode').text:
            tab('提交').click('js')
            return print(f'{wb}验证码识别成功')
        else:
            tab('tag:div@@class=tncode_refresh', timeout=1).click()
            print('.', end='')
            Verification_code(tab, wb)


def signin(tab, name, AccountNumber):
    '''签到'''
    global os_name
    if os_name != 'Windows':
        File_Path = '/root/python/log/'
    else:
        File_Path = './log/'
    tab.get('https://wxg1425obh.com/plugin.php?id=k_misign:sign')
    shu = 0
    while 'liang' not in tab('t:div@@class=user').text:
        shu += 1
        if shu % 10 == 0:
            tab.refresh()
        tab.wait(1)
    签到按钮 = tab('tag:a@@class=btn J_chkitot')
    if 签到按钮:
        签到按钮.click()
    else:
        # with open(f'{File_Path}{datetime.date.today()}.log',
        #           'a+',
        #           encoding='utf-8') as f:
        #     f.write(f'{str(datetime.date.today())} {name} 已经签到\n')
        return print(f'{name} 已经签到')
    tab.listen.start('/captcha/tncode.php')  # 开始监听，指定获取包含该文本的数据包
    tab('tag:div@@id=tncode').click()
    Verification_code(tab, '验证码')
    tab.listen.stop()  # 停止监听
    with open(f'{File_Path}{datetime.date.today()}.log',
              'a+',
              encoding='utf-8') as f:
        f.write(f'{str(datetime.date.today())} {name} 签到成功\n')

    return print(f'{name} 签到成功')


def Login_Account(tab, name, AccountNumber):
    '''登录账号'''
    tab.get('https://wxg1425obh.com/member.php?mod=logging&action=login')
    tab.wait.eles_loaded('@name=username')
    tab('@name=username').input(AccountNumber['username'], by_js=True)
    tab('@name=password').input(AccountNumber['password'], by_js=True)
    tab.listen.start('/captcha/tncode.php')  # 开始监听，指定获取包含该文本的数据包
    tab('tag:div@@id=tncode').click()
    Verification_code(tab, '登录')
    tab.listen.stop()  # 停止监听
    tab.wait(2)
    signin(tab, name, AccountNumber)
    return


def main():
    '''主函数'''
    # 登录账号
    liang008 = {'username': '17677051263@163.com', 'password': 'Lz19990311.'}
    liang007 = {'username': '3233537658@qq.com', 'password': 'Lz19990311.'}
    if tab('liang'):
        if tab('liang').text == 'liang007':
            signin(tab, 'liang007', liang007)
            tab.wait(1)
            tab('@id=deanmemberinfo').hover()
            tab('tag:a@@text()=退出').click()
            tab.wait(3)
            Login_Account(tab, 'liang008', liang008)
        else:
            signin(tab, 'liang008', liang008)
            tab.wait(1)
            tab('@id=deanmemberinfo').hover()
            tab('tag:a@@text()=退出').click()
            tab.wait(3)
            Login_Account(tab, 'liang007', liang007)

    else:
        print('未找到账号，请先登录')
        Login_Account(tab, 'liang007', liang007)
        tab.wait(1)
        tab('@id=deanmemberinfo').hover()
        tab('tag:a@@text()=退出').click()
        tab.wait(3)
        Login_Account(tab, 'liang008', liang008)

    # 退出浏览器
    browser.quit()


if __name__ == '__main__':
    main()
